﻿using System;
using System.Linq;
using System.Reflection;
using NHibernate;

namespace ControleRepresentante.Logic.Repositories
{
    public interface IRepositoryCreator
    {
        IRepository Create(IRepositoryConfiguration repositoryConfiguration, ISession session, object[] repositoryParameters);
    }

    public class RepositoryCreator<T> : IRepositoryCreator
        where T : class, IRepository
    {
        private readonly IRepository m_Repository;

        public RepositoryCreator()
        {
        }

        public RepositoryCreator(IRepository repository)
        {
            m_Repository = repository;
        }

        public IRepository Create(IRepositoryConfiguration repositoryConfiguration, ISession session, object[] repositoryParameters)
        {
            if (m_Repository != null) return m_Repository;

            try
            {
                object[] bindingAttr = new object[]{repositoryConfiguration, session}.Union(repositoryParameters).ToArray();
                return (T)Activator.CreateInstance(typeof(T), bindingAttr);
            }
            catch (TargetInvocationException e)
            {
                throw e.InnerException ?? e;
            }
        }
    }
}